package com.nicole.exception;

import cn.dev33.satoken.exception.SaTokenException;
import cn.hutool.core.util.StrUtil;
import com.nicole.comm.Result;
import com.nicole.comm.SysConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result handleBusinessException(BusinessException e) {
        log.error("[业务错误] 错误码：{},异常信息：{}", e.getCode(), e.getErrorMsg());
        return StrUtil.isEmpty(e.getCode()) ? Result.fail(e.getErrorMsg()) : Result.fail(e.getCode(), e.getErrorMsg());
    }

    /**
     * 处理Sa-Token异常 如登录报错
     */
    @ExceptionHandler(SaTokenException.class)
    public Result handleSaTokenException(SaTokenException e) {
        log.error("[Sa-Token错误] 错误代码：{}", e.getCode());
        return Result.fail(400, String.valueOf(e.getCode()));
    }

    /**
     * @Validated 字段校验失败处理
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleValidationException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.fail(SysConstants.VALIDATE_ERROR_CODE, message);
    }


    /**
     * 处理其他未捕获异常,兜底处理
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("[系统错误] 错误信息：{}", e.getMessage());
        return Result.fail(ExceptionEnum.SYS_ERROR);
    }
}
